<?php
/*
/ Ajax Functions file. Functions in this file are used throughout ZPanel to complete dynamic tasks.
/
/ Created: 5/11/2006
/ Last Edited: 7/27/2006 - KGA
*/
##################################################
# Declare Functions
##################################################
require_once('xajax/xajax.inc.php');
$xajax = new xajax();
#$xajax->debugOn();
$xajax->registerFunction("MyAccount_Update");
$xajax->registerFunction("ChangePasswd");
$xajax->registerFunction("stat_updatestyle");
$xajax->registerFunction("adm_installer_dlzip");
$xajax->registerFunction("adm_installer_addsql");
$xajax->registerFunction("AddDomain");
$xajax->registerFunction("AddParkedDomain");
$xajax->registerFunction("AddSubdomain");
$xajax->registerFunction("UpdateDomain");

### Show function code ###

// Function: Update My Account
// Creation Date: 5/11/2006
// Alter Date: 8/07/2006
// Usage: Updates the information in the My Account page.
function MyAccount_Update($firstname,$lastname,$gender,$email,$phone,$address,$address2,$city,$state,$country,$zip,$date_format,$time_format) {
	global $DB,$_SESSION;

	$DB->Execute("UPDATE accounts SET firstname = '$firstname',lastname = '$lastname',gender = '$gender',email = '$email',phone = '$phone',address = '$address',address2 = '$address2',city = '$city',state = '$state',zip = '$zip',country = '$country',date_format = '$date_format',time_format = '$time_format' WHERE username = '".$_SESSION['username']."'");

	// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    
    // add a command to the response to assign the innerHTML attribute of
    // the element with id="SomeElementId" to whatever the new content is
    $objResponse->addScript("showconf();");
    
    //return the XML response generated by the xajaxResponse object
    return $objResponse->getXML();
}

function ChangePasswd($newpass,$confirmpass,$secq,$seca) {
	global $DB,$_SESSION,$user;

	$updatestring = 'SET ';

	if ($newpass == $confirmpass) {
		$updatestring = "password='".md5($newpass)."'";
		$updatedpassword = 1;
	}
  
	if ($secq != $user['secret_question']) {
		if ($seca != '') {
			if ($updatedpassword) { $updatestring .= ','; }
				$updatestring .= "secret_question='".$secq."',secret_answer='".md5($seca)."'";
				$alreadyupdated = '1';
			}
	}
  
	if (!isset($alreadyupdated)) {
		if (md5($seca) != $user['secret_answer']) {
			if ($updatedpassword) { $updatestring .= ','; }
				$updatestring .= "secret_answer='".md5($seca)."'";
			}
	}

 	$DB->Execute("UPDATE accounts SET ".$updatestring." WHERE username = '".$_SESSION['username']."'");

	
	// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    
    // add a command to the response to assign the innerHTML attribute of
    // the element with id="SomeElementId" to whatever the new content is
    $objResponse->addScript("showconf();");
    $objResponse->addScript("document.getElementById('passconfirm').innerHTML='Enter a New Password';");
    $objResponse->addScript("document.form1.new_passwd.value = '';");
    $objResponse->addScript("document.form1.confirm_new.disabled = true;");
    $objResponse->addScript("document.form1.confirm_new.value = '';");
    $objResponse->addScript("document.form1.secret_answer.value = '';");
    
    //return the XML response generated by the xajaxResponse object
    return $objResponse->getXML();
}

// Function: Update Stat Style
// Creation Date: 7/27/2006
// Alter Date: 7/27/2006
// Usage: Updates the style for the page being edited.
function stat_updatestyle($page,$style) {
	global $DB;

	$DB->Execute("UPDATE mod_counter SET style='$style' WHERE id='$page'");

        // Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	//return the XML response generated by the xajaxResponse object
	return $objResponse->getXML();
}

// Function: Installer - Download .ZIP
// Creation Date: 7/27/2006
// Alter Date: 7/27/2006
// Usage: When an installer is being added from Zantastico's DB,
//        this downloads the ZIP file containing the script.
function adm_installer_dlzip($url) {
	global $settings;

	ini_set('max_execution_time','50000');
	set_time_limit('50000');

	// Deciding destination
	$archives = $setttings['path'].'/modules/installscripts/archives/';

	// Getting filename
	$filename = substr(strrchr($url, '/'), 1);

	// Downloading ZIP file
	$handle = fopen($archives.$filename, 'w+') or die ('Could not open file');
	fwrite($handle, file_get_contents($url)) or die ('Could not save');
	fclose($handle);

        // Instantiate the xajaxResponse object
	$objResponse = new xajaxResponse();

	//return the XML response generated by the xajaxResponse object
	return $objResponse->getXML();
}

function adm_installer_addsql($id) {
        global $db_host,$db_user,$db_pass,$db_name;

	// Get information from Zantastico's DB
	$dbconn = mysql_connect('mysql.zee-way.com','zantastico','');
	mysql_select_db('zp_zantastico',$dbconn);

	$sql = "SELECT * FROM zantastico WHERE id='".$id."'";
	$result = mysql_query($sql,$dbconn);
	$installer = mysql_fetch_assoc($result);	

        // Getting filename
        $filename = substr(strrchr($installer['zip'], '/'), 1);

	// Transfer the information to this ZPanel
        $mysql = new MySQL($db_host,$db_user,$db_pass,$db_name);
        $sql = sprintf("INSERT INTO zantastico (name,version,website,welcome,instructions,finalmessage,exampledir,catid,zip,uniquekey) VALUES ('%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s')",
		mysql_real_escape_string($installer['name']),
                mysql_real_escape_string($installer['version']),
                mysql_real_escape_string($installer['website']),
                mysql_real_escape_string($installer['welcome']),
                mysql_real_escape_string($installer['instructions']),
                mysql_real_escape_string($installer['finalmessage']),
                mysql_real_escape_string($installer['exampledir']),
                mysql_real_escape_string($installer['catid']),
                mysql_real_escape_string($filename),
                mysql_real_escape_string($installer['uniquekey']));
        $result = $mysql->query($sql);

        // Get Category information
        $sql = "SELECT * FROM zantastico_categories WHERE id='".$installer['catid']."'";
        $result = mysql_query($sql,$dbconn);
        $category = mysql_fetch_assoc($result);

	// Create category
        $sql = sprintf("INSERT INTO zantastico_categories (id,name) VALUES ('%s','%s')",
                $category['id'],
                str_replace("'",'&apos;',$category['name']));
	$result = $mysql->query($sql);

        // Free the result in memory
        $mysql->close();

        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();

        //return the XML response generated by the xajaxResponse object
        return $objResponse->getXML();
}

function AddDomain($dom,$path) {
        global $_SESSION,$DB;

        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();

	// Is this is a subdomain?
	$cutdomain = explode('.',$dom);
	if (count($cutdomain) > 2) { $subdomain = 1; }else{ $subdomain = 0; }

	if ($subdomain) {
		// Make sure the root domain isn't registered...
		// Only root domains use this function

		$result = $DB->GetOne("SELECT COUNT(*) FROM domains WHERE domain='".$cutdomain[1].'.'.$cutdomain[2]."'");

		if ($result > 0) {
			// Domain exists, quit
			$objResponse->addScript("document.getElementById('add_domain_status').innerHTML='<font color=red>You must add subdomains using the <a href=\"?cat=domainadmin&page=subdomains\">Subdomains</a> page.</font>';");
			return $objResponse->getXML();
			exit;
		}
	}

        // Make sure the domain isn't already added 
	$result = $DB->GetOne("SELECT COUNT(*) FROM domains WHERE domain='$dom'");

	if ($result == 0) {
		// Make sure it's registered
		$nslookup = strtolower(shell_exec("nslookup $dom"));
		if ((strpos($nslookup,'non-existant domain') !== false) ||
		    (strpos($nslookup,'can\'t find') !== false)) {
			// Domain doesn't exist
			$objResponse->addScript("document.getElementById('add_domain_status').innerHTML='<font color=red>That domain does not exist. If it was just registered, please allow up to 12 hours before it can be detected.</font>';");
		}else{

			$DB->Execute("INSERT INTO domains (domain,user,date,path) VALUES ('$dom','".$_SESSION['username']."','".time()."','$path')");

			CreateVH();

			$objResponse->addScript("document.location='?cat=domainadmin&page=domains&added';");
		}
	}else{
		$objResponse->addScript("document.getElementById('add_domain_status').innerHTML='<font color=red>That domain already exists.</font>';");
	}

	//return the XML response generated by the xajaxResponse object
	return $objResponse->getXML();
}

function AddSubdomain($dom,$master,$path) {
        global $_SESSION,$DB;

        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();

        // Make sure the domain isn't already added
	$result = $DB->GetOne("SELECT COUNT(*) FROM domains WHERE domain='$dom'");

        if ($result == 0) {
		$DB->Execute("INSERT INTO domains (domain,masterdomain,user,date,path) VALUES ('$dom','$master','".$_SESSION['username']."','".time()."','$path')");

	        CreateVH();

        	$objResponse->addScript("document.location='?cat=domainadmin&page=subdomains&added';");
        }else{
                $objResponse->addScript("document.getElementById('add_domain_status').innerHTML='<font color=red>That subdomain already exists.</font>';");
        }

        //return the XML response generated by the xajaxResponse object
        return $objResponse->getXML();
}

function AddParkedDomain($dom) {
        global $_SESSION,$DB;

        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();

        // Make sure the domain isn't already added
	$result = $DB->GetOne("SELECT COUNT(*) FROM domains WHERE domain='$dom'");

        if ($result == 0) {
		$DB->Execute("INSERT INTO domains (domain,user,date,parked) VALUES ('$dom','".$_SESSION['username']."','".time()."','1')");

                CreateVH();

                $objResponse->addScript("document.location='?cat=domainadmin&page=parked_domains&added';");
        }else{
                $objResponse->addScript("document.getElementById('add_domain_status').innerHTML='<font color=red>That domain already exists. It may be an active domain.</font>';");
        }

        //return the XML response generated by the xajaxResponse object
        return $objResponse->getXML();
}

function UpdateDomain($dom,$path,$sub=0) {
        global $_SESSION,$DB;

        // Instantiate the xajaxResponse object
        $objResponse = new xajaxResponse();

        // Make sure the domain isn't already added
	$DB->Execute("UPDATE domains SET path='$path' WHERE domain='$dom' AND user='".$_SESSION['username']."'");

	// Refresh the VHosts
	CreateVH();

	if ($sub) {
		$objResponse->addScript("document.location='?cat=domainadmin&page=subdomains&updated';");
	}else{
		$objResponse->addScript("document.location='?cat=domainadmin&page=domains&updated';");
	}
	return $objResponse->getXML();
}

##################################################
# Process requests
##################################################
$xajax->processRequests();

?>
